home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12732 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: hursley.ibm.com!news
  2. From: Max Waterman <dwater@wight.hursley.ibm.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Is This Bad Coding Practice?
  5. Date: Tue, 02 Apr 1996 14:32:06 +0100
  6. Organization: IBM UK Laboratories Ltd.
  7. Message-ID: <31612C56.4487@wight.hursley.ibm.com>
  8. References: <4jgnt2$9d1@loki.tor.hookup.net> <828135115snz@genesis.demon.co.uk>
  9. NNTP-Posting-Host: wight.hursley.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (X11; I; AIX 2)
  14.  
  15. In article <4jgnt2$9d1@loki.tor.hookup.net>
  16.            Rajendra_Singh@msn.com "Rajendra Singh" writes:
  17.  
  18. >int main(int argc, char *argv[])
  19. >   {
  20. >   char string[128];
  21. >   char *func1(void);
  22. >
  23. >   strcpy(string, func1());
  24. >   return 0;
  25. >   }
  26. >
  27. >char *func1(void)
  28. >   {
  29. >   char test[100];
  30. >
  31. >   sprintf(test, "Test:  %d", 1);
  32. >   return test;
  33. >   }
  34. >
  35. >... since I am using the value returned from func1() immediately (in
  36. >main()), is this reliable?
  37.  
  38. As others have pointed out; no, this is bad code. It may well work under
  39. debug mode, but as soon as you turn any significant optimisations on,
  40. code relying on this behaviour will fail.
  41.  
  42. Alternatives I can think of would be to :
  43.  
  44. 1) declare test[100] as static;
  45.  
  46. 2) declare automatic test in main() and pass address to func1;
  47.  
  48. 3) malloc()/free() some memory in main() for func1() to use - pass
  49. address of memory to func1();
  50.  
  51. Option 2) in the case above would be my favoured choice.
  52.  
  53. It also strikes me as not good practice to call a function in the call
  54. to another. In most cases, it is best to call func1() first, then call 
  55. strcpy()/whatever.
  56.  
  57. I guess the #include's where ommited for bevity?
  58.  
  59. Also, I don't think there is a need to declare the args to main() if
  60. they're not being used. Suggest int main( void ) would be better.
  61. Anyone?
  62.  
  63. Max.
  64. -- 
  65.     ___                      mailto:max@lton.u-net.com 
  66.   /  /  /  _       /     /  _  __ __   _   __   _
  67.  /  /  / /_/ |/  /  /  / /_/  /  /_   /_/ / / / /_/ /| /
  68. /  /  / /  / /|  /_/_/ /  /  /  /_  /  |  / / / /  / / |/
  69.